/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imat;

import java.awt.Dimension;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.swing.JPanel;
import se.chalmers.ait.dat215.project.Product;

/**
 *
 * @author Andreas
 */
public class SearchPresenter {
    
    private SearchView searchView;

    public SearchPresenter(SearchView view) {
        searchView = view;
    }

    public void search(String str) {
        search(str, false);
    }

    public void search(String str, boolean all) {
        List<Product> products = DataHandler.getInstance().findProducts(str);
        System.out.println("Search for \""+ str +"\"");
        searchView.getProductsPanel().removeAll();
        int cap = (all || products.size()<8) ? products.size() : 8;


        Product[] pr = new Product[cap];
        pr = products.toArray(pr);

        Arrays.sort(pr, new Comparator<Product>() {

            public int compare(Product o1, Product o2) {
                if (DataHandler.getInstance().isFavorite(o1)) {
                    return -1;
                }
                else if (DataHandler.getInstance().isFavorite(o2)) {
                    return 1;
                }
                return 0;
            }
        });


        for (int i=0; i<cap; i++) {
            addProduct(pr[i]);
        }
        

        if (products.size() > 12 && !all) {
            searchView.getShowAllPanel().setVisible(true);
        }
        else {
            searchView.getShowAllPanel().setVisible(false);
        }
        searchView.getProductsPanel().repaint();
        searchView.getTitle().setText("Sök efter \"" + str + "\". "+cap+"/"+products.size()+" träffar visas.");

        // Scrollbar fix
        JPanel panel = searchView.getScrollPanel();
        System.out.println("panelSize: "+panel.getSize());
        int w = panel.getSize().width;
        int nrW = 1;
        if (w >= 795)
            nrW = 3;
        else if (w >= 530)
            nrW = 2;
        int rows = (cap / nrW) + 1;
        panel.setPreferredSize(new Dimension(0, 10+rows*130));
        panel.revalidate();
        System.out.println("panelPreferredSize: "+panel.getPreferredSize());
    }

    public void addProduct(Product p) {
        ProductView view = new ProductView();
        view.setProduct(p);
        searchView.getProductsPanel().add(view);
        searchView.validate();
    }
}
